// 🚀 PWA 安装提示管理器
// 功能：管理Web App安装提示，提供用户友好的安装体验

class PWAInstallManager {
  constructor() {
    this.deferredPrompt = null;
    this.isStandalone = window.matchMedia('(display-mode: standalone)').matches ||
                       window.navigator.standalone ||
                       document.referrer.includes('android-app://');
    
    this.init();
  }

  init() {
    // 监听beforeinstallprompt事件
    window.addEventListener('beforeinstallprompt', (e) => {
      e.preventDefault();
      this.deferredPrompt = e;
      this.showInstallPromotion();
    });

    // 监听appinstalled事件
    window.addEventListener('appinstalled', () => {
      console.log('✅ PWA已安装');
      this.hideInstallPromotion();
      this.trackInstall('installed');
    });

    // 检查是否已经安装
    this.checkInstallationStatus();
    
    // 添加安装按钮事件监听
    this.setupInstallButton();
  }

  // 检查安装状态
  checkInstallationStatus() {
    if (this.isStandalone) {
      console.log('📱 已在独立模式下运行');
      this.hideInstallPromotion();
      return;
    }

    // 检查相关应用是否已安装
    if ('getInstalledRelatedApps' in navigator) {
      navigator.getInstalledRelatedApps().then(apps => {
        if (apps.length > 0) {
          console.log('📲 检测到已安装的相关应用');
          this.hideInstallPromotion();
        }
      });
    }
  }

  // 显示安装提示
  showInstallPromotion() {
    if (this.isStandalone) return;

    const installBanner = this.createInstallBanner();
    document.body.appendChild(installBanner);
    
    // 显示动画
    setTimeout(() => {
      installBanner.classList.add('show');
    }, 1000);

    this.trackInstall('prompt_shown');
  }

  // 创建安装提示横幅
  createInstallBanner() {
    const banner = document.createElement('div');
    banner.id = 'pwa-install-banner';
    banner.className = 'pwa-install-banner';
    banner.innerHTML = `
      <div class="install-content">
        <div class="install-icon">
          <img src="/images/icons/icon-72x72.png" alt="精英杂志">
        </div>
        <div class="install-info">
          <h3>安装精英杂志</h3>
          <p>获得更好的阅读体验，支持离线阅读</p>
        </div>
        <div class="install-actions">
          <button id="install-button" class="install-btn install-btn-primary">
            立即安装
          </button>
          <button id="install-dismiss" class="install-btn install-btn-secondary">
            稍后
          </button>
        </div>
      </div>
      <div class="install-progress" style="display: none;">
        <div class="progress-bar"></div>
        <span class="progress-text">正在安装...</span>
      </div>
    `;

    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
      .pwa-install-banner {
        position: fixed;
        bottom: 20px;
        left: 20px;
        right: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        border-radius: 12px;
        box-shadow: 0 8px 32px rgba(0,0,0,0.3);
        z-index: 10000;
        transform: translateY(150%);
        transition: transform 0.3s ease-out;
        max-width: 500px;
        margin: 0 auto;
      }

      .pwa-install-banner.show {
        transform: translateY(0);
      }

      .install-content {
        display: flex;
        align-items: center;
        gap: 15px;
      }

      .install-icon img {
        width: 48px;
        height: 48px;
        border-radius: 12px;
      }

      .install-info {
        flex: 1;
      }

      .install-info h3 {
        margin: 0 0 5px 0;
        font-size: 16px;
        font-weight: 600;
      }

      .install-info p {
        margin: 0;
        font-size: 14px;
        opacity: 0.9;
      }

      .install-actions {
        display: flex;
        gap: 10px;
      }

      .install-btn {
        padding: 8px 16px;
        border: none;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
      }

      .install-btn-primary {
        background: white;
        color: #667eea;
      }

      .install-btn-primary:hover {
        background: #f8f9fa;
        transform: translateY(-1px);
      }

      .install-btn-secondary {
        background: rgba(255,255,255,0.2);
        color: white;
        border: 1px solid rgba(255,255,255,0.3);
      }

      .install-btn-secondary:hover {
        background: rgba(255,255,255,0.3);
      }

      .install-progress {
        margin-top: 15px;
        text-align: center;
      }

      .progress-bar {
        width: 100%;
        height: 4px;
        background: rgba(255,255,255,0.3);
        border-radius: 2px;
        overflow: hidden;
        margin-bottom: 8px;
      }

      .progress-bar::after {
        content: '';
        display: block;
        width: 0%;
        height: 100%;
        background: white;
        border-radius: 2px;
        animation: progress-animation 2s ease-out forwards;
      }

      @keyframes progress-animation {
        to { width: 100%; }
      }

      .progress-text {
        font-size: 12px;
        opacity: 0.8;
      }

      @media (max-width: 480px) {
        .pwa-install-banner {
          bottom: 10px;
          left: 10px;
          right: 10px;
          padding: 15px;
        }

        .install-content {
          flex-direction: column;
          text-align: center;
        }

        .install-actions {
          justify-content: center;
          width: 100%;
        }
      }
    `;
    document.head.appendChild(style);

    return banner;
  }

  // 设置安装按钮事件
  setupInstallButton() {
    document.addEventListener('click', (e) => {
      if (e.target.id === 'install-button') {
        this.handleInstallClick();
      } else if (e.target.id === 'install-dismiss') {
        this.hideInstallPromotion();
        this.trackInstall('dismissed');
      }
    });
  }

  // 处理安装点击
  async handleInstallClick() {
    if (!this.deferredPrompt) {
      console.log('❌ 安装提示不可用');
      return;
    }

    const banner = document.getElementById('pwa-install-banner');
    const content = banner.querySelector('.install-content');
    const progress = banner.querySelector('.install-progress');

    // 显示进度条
    content.style.display = 'none';
    progress.style.display = 'block';

    // 显示安装提示
    this.deferredPrompt.prompt();
    
    // 等待用户选择
    const { outcome } = await this.deferredPrompt.userChoice;
    
    console.log(`📱 用户安装选择: ${outcome}`);
    
    if (outcome === 'accepted') {
      this.trackInstall('accepted');
      progress.querySelector('.progress-text').textContent = '安装中...';
    } else {
      this.trackInstall('rejected');
      this.hideInstallPromotion();
    }

    this.deferredPrompt = null;
  }

  // 隐藏安装提示
  hideInstallPromotion() {
    const banner = document.getElementById('pwa-install-banner');
    if (banner) {
      banner.classList.remove('show');
      setTimeout(() => {
        banner.remove();
      }, 300);
    }
  }

  // 创建自定义安装按钮
  createInstallButton(text = '安装应用') {
    const button = document.createElement('button');
    button.className = 'custom-install-btn';
    button.textContent = text;
    button.addEventListener('click', () => this.handleInstallClick());
    return button;
  }

  // 跟踪安装事件
  trackInstall(action) {
    // 发送到分析服务
    if (typeof gtag !== 'undefined') {
      gtag('event', 'pwa_install', {
        event_category: 'PWA',
        event_label: action,
        value: 1
      });
    }

    // 本地存储统计
    const stats = JSON.parse(localStorage.getItem('pwa-install-stats') || '{}');
    stats[action] = (stats[action] || 0) + 1;
    stats.lastAction = new Date().toISOString();
    localStorage.setItem('pwa-install-stats', JSON.stringify(stats));
  }

  // 获取安装统计
  getInstallStats() {
    return JSON.parse(localStorage.getItem('pwa-install-stats') || '{}');
  }

  // 检查是否可以安装
  canInstall() {
    return !!this.deferredPrompt && !this.isStandalone;
  }
}

// 🚀 初始化PWA安装管理器
if ('serviceWorker' in navigator) {
  const pwaInstallManager = new PWAInstallManager();
  
  // 暴露到全局作用域
  window.pwaInstallManager = pwaInstallManager;
  
  console.log('🚀 PWA安装管理器已初始化');
} else {
  console.log('❌ 浏览器不支持PWA');
}